package com.craftworks.rtmp.amf0;

import com.craftworks.util.BigEndian;

import java.util.LinkedHashMap;
import java.util.Map;

public class ObjectType extends DataType
{
    private static final String TYPE_NAME = "ObjectType";

    private Map<String, ObjectProperty> properties;

    public ObjectType(byte[] bytes, int offset)
    {
        super(0x03, bytes, offset);
    }

    @Override
    protected void decode(byte[] bytes, int offset)
    {
        if (BigEndian.getUINT8(bytes, offset) != type)
            throw new IllegalArgumentException("incorrect bytes encoding");

        size = 1;
        offset += 1;
        properties = new LinkedHashMap<>();
        while (!AMF0.isObjectEndProperty(bytes, offset))
        {
            ObjectProperty property = new ObjectProperty(bytes, offset);
            size += property.getSize();
            offset += property.getSize();
            properties.put(property.getName(), property);
        }
        size += 3;
    }

    @Override
    public String stringValue()
    {
        throw new UnsupportedOperationException(TYPE_NAME);
    }

    @Override
    public Double doubleValue()
    {
        throw new UnsupportedOperationException(TYPE_NAME);
    }

    @Override
    public Boolean booleanValue()
    {
        throw new UnsupportedOperationException(TYPE_NAME);
    }

    @Override
    public Map<String, ObjectProperty> propertyValue()
    {
        return properties;
    }

    @Override
    public String toString()
    {
        StringBuilder sbuf = new StringBuilder();
        sbuf.append("ObjectType{\n");
        for (Map.Entry<String, ObjectProperty> entry : properties.entrySet())
            sbuf.append("  -").append(entry.getValue()).append("\n");
        sbuf.append("}");
        return sbuf.toString();
    }
}
